import { StatusPulishServerPromiseClient } from "./gen/disservice_grpc_web_pb";
import { 
  HisTableResult, 
  HisRecordTableSetRequest, 
  ULRequest
} from "./gen/disservice_pb";
import { Empty } from "google-protobuf/google/protobuf/empty_pb";

// 创建 gRPC 客户端实例
const client = new StatusPulishServerPromiseClient('http://localhost:3000', null, {
  format: 'text',
  suppressCorsPreflight: false
});

// 创建 gRPC 服务类
class GrpcService {
  constructor() {
    this.client = client;
  }

  // 获取 DIS 状态
  async queryDISStatus() {
    try {
      const request = new Empty();
      const response = await this.client.queryDISStatus(request, {});
      return {
        success: true,
        data: response ? response.toObject() : null
      };
    } catch (error) {
      console.error('Query DIS Status Error:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 获取队列信息
  async queryQueueInfos() {
    try {
      const request = new Empty();
      const response = await this.client.queryQueueInfos(request, {});
      return {
        success: true,
        data: response.toObject()
      };
    } catch (error) {
      console.error('Query Queue Infos Error:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 获取客户端列表
  async queryClientList() {
    try {
      const request = new Empty();
      const response = await this.client.queryClientList(request, {});
      return {
        success: true,
        data: response.toObject()
      };
    } catch (error) {
      console.error('Query Client List Error:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 获取历史记录表
  async queryHisRecordTable() {
    try {
      const request = new Empty();
      const response = await this.client.queryHisRecordTable(request, {});
      return {
        success: true,
        data: response.toObject()
      };
    } catch (error) {
      console.error('Query History Record Table Error:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 设置历史记录表
  async setHisRecordTable(records) {
    try {
      const request = new HisRecordTableSetRequest();
      if (records && Array.isArray(records)) {
        records.forEach(record => {
          const hisRecord = new HisTableResult.HisTableRecord();
          hisRecord.setDeviceid(record.deviceid || '');
          hisRecord.setPrn(record.prn || '');
          hisRecord.setFinished(record.finished || 0);
          hisRecord.setTimestamp(record.timestamp || 0);
          request.addRecords(hisRecord);
        });
      }
      const response = await this.client.setHisRecordTable(request, {});
      return {
        success: true,
        data: response.toObject()
      };
    } catch (error) {
      console.error('Set History Record Table Error:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 立即上传包裹数据
  async uploadBagDataImmediately(infos) {
    try {
      const request = new ULRequest();
      if (infos && Array.isArray(infos)) {
        infos.forEach(info => {
          const ulInfo = new ULRequest.ULInfo();
          ulInfo.setDeviceId(info.device_id || '');
          ulInfo.setPrn(info.prn || '');
          ulInfo.setUploadFilebit(info.upload_filebit || 0);
          request.addInfos(ulInfo);
        });
      }
      const response = await this.client.uploadBagDataImmediately(request, {});
      return {
        success: true,
        data: response.toObject()
      };
    } catch (error) {
      console.error('Upload Bag Data Immediately Error:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 查询立即上传进度
  async queryIMUploadingProgress() {
    try {
      const request = new Empty();
      const response = await this.client.queryIMUploadingProgress(request, {});
      return {
        success: true,
        data: response.toObject()
      };
    } catch (error) {
      console.error('Query IM Uploading Progress Error:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  // 获取连接状态
  isConnected() {
    return this.client && this.client.client_;
  }

  // 设置服务器地址
  setServerUrl(url) {
    if (url && typeof url === 'string') {
      this.client = new StatusPulishServerPromiseClient(url, null, {
        format: 'text',
        suppressCorsPreflight: false
      });
    } else {
      // 默认配置
      this.client = new StatusPulishServerPromiseClient('http://localhost:22002', null, {
        format: 'text',
        suppressCorsPreflight: false
      });
    }
  }
}

// 创建服务实例
const grpcService = new GrpcService();

export default grpcService;